<template>
  <div class="chat-root">
    <div class="chat-bg"></div>
    <el-container class="chat-container">
      <el-aside class="chat-aside">
        <!-- 顶部标题 -->
        <div style="padding: 16px; text-align: center; font-weight: bold; font-size: 18px; flex-shrink: 0;">历史会话</div>
        <el-button type="primary" style="width: 90%;flex-shrink: 0;margin: auto;" @click="createChat">新建会话</el-button>
        <!-- 可滚动历史会话列表 -->
        <el-scrollbar style="flex: 1;text-align: left;">
          <el-menu :default-active="String(selectedChatId)" @select="handleSelectChat" style="border: none;">
            <el-menu-item v-for="chat in chatList" :key="chat.id" :index="String(chat.id)" style="display: flex; align-items: center; justify-content: space-between;">
              <span @click.stop="handleSelectChat(chat.id)" style="flex:1;cursor:pointer;">{{ chat.title }}</span>
              <el-button type="text" style="color: #f56c6c; margin-left: 8px;" @click.stop="handleDeleteChat(chat.id)">删除</el-button>
            </el-menu-item>
          </el-menu>
        </el-scrollbar>
        <!-- 固定底部退出按钮 -->
        <el-button type="danger" icon="el-icon-switch-button" style="margin: 14px; width: 90%; flex-shrink: 0;" @click="logout" plain>退出登录</el-button>
      </el-aside>
      <el-container>
        <!-- 顶部header固定 -->
        <el-header class="chat-header">历史建筑信息交互助手</el-header>
        <!-- 聊天内容区可滚动 -->
        <el-main class="chat-main">
          <div class="chat-scroll-area">
            <!-- 聊天内容渲染区 -->
            <el-scrollbar :style="{height: '100%'}">
              <div v-for="(item, idx) in messageList" :key="idx" style="margin-bottom: 16px;">
                <!-- 用户消息 -->
                <div v-if="item.question" style="display: flex; justify-content: flex-end; align-items: flex-end;">
                  <div style="margin-right: 8px;">
                    <div class="chat-bubble user-bubble">{{ item.question }}</div>
                    <!-- 这里插入图片预览 -->
                    <div v-if="item.imageUrl" style="margin-top: 6px; text-align: right;">
                      <img :src="item.imageUrl" style="width: 200px; height: 150px; object-fit: cover; border-radius: 8px;" />
                    </div>
                  </div>
                  <img src="/user-avatar.png" class="chat-avatar" alt="user" />
                </div>
                <!-- 助手消息 -->
                <div v-if="item.answer" style="display: flex; justify-content: flex-start; align-items: flex-end;">
                  <img src="/assistant-avatar.png" class="chat-avatar" alt="assistant" />
                  <div style="margin-left: 8px;">
                    <div class="chat-bubble assistant-bubble" v-html="item.answer"></div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>
          <!-- 底部输入区固定 -->
          <div class="chat-input-bar">
            <!-- 输入区内容 -->
            <div style="max-width: 1300px; margin: 0 auto; padding: 16px 0;">
              <div v-if="image" style="color: #888; font-size: 13px; margin-bottom: 8px; display: flex; align-items: center; padding-left: 20px;">
                <span>已选择图片：{{ image.name }}</span>
                <el-button type="text" size="small" @click="cancelImage" style="margin-left: 8px; color: #f56c6c;">取消选择</el-button>
              </div>
              <div style="display: flex; align-items: flex-end; padding-right: 20px;">
                <el-input v-model="question" type="textarea" :rows="2" placeholder="请输入你的问题..." style="margin-right: 28px; flex: 1; left: 20px;" />
                <el-upload :show-file-list="false" :before-upload="beforeUpload">
                  <el-button style="margin-right: 8px">图片</el-button>
                </el-upload>
                <el-button type="primary" @click="handleSend" :loading="loading">发送</el-button>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const userId = localStorage.getItem('userId');
const chatList = ref([]); // 会话列表
const selectedChatId = ref(null); // 当前选中会话id
const messageList = ref([]); // 当前会话消息
const question = ref('');
const loading = ref(false);
const image = ref(null);

const cancelImage = () => {
  image.value = null;
};

const fetchChatList = async () => {
  if (!userId) return;
  try {
    const res = await axios.get(`/api/chat/list/${userId}`);
    chatList.value = res.data;
    if (chatList.value.length && !selectedChatId.value) {
      selectedChatId.value = chatList.value[0].id;
      fetchMessageList(selectedChatId.value);
    }
  } catch (e) {
    ElMessage.error('会话列表加载失败');
  }
};

const fetchMessageList = async (chatId) => {
  try {
    const res = await axios.get(`/api/chat/history/${chatId}`);
    messageList.value = res.data;
  } catch (e) {
    ElMessage.error('消息加载失败');
  }
};

const handleSelectChat = (chatId) => {
  selectedChatId.value = Number(chatId);
  fetchMessageList(selectedChatId.value);
};

const beforeUpload = (file) => {
  image.value = file;
  return false;
};

const handleSend = async () => {
  if (!question.value && !image.value) return ElMessage.warning('请输入问题或选择图片');
  if (!selectedChatId.value) return ElMessage.warning('请先选择会话');
  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('data', JSON.stringify({
      chatId: selectedChatId.value,
      userId,
      question: question.value
    }));
    if (image.value) formData.append('image0', image.value); // 字段名必须为 image0
    const res = await axios.post('/api/chat/send', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    messageList.value.push(res.data);
    question.value = '';
    image.value = null;
    await fetchChatList(); // 发送消息后自动刷新会话列表，更新标题
  } catch (e) {
    ElMessage.error('发送失败');
  }
  loading.value = false;
};

const createChat = async () => {
  try {
    const res = await axios.post('/api/chat/create', { userId, title: '' }); // 直接传空标题
    chatList.value.unshift(res.data);
    selectedChatId.value = res.data.id;
    messageList.value = [];
  } catch (e) {
    ElMessage.error('新建会话失败');
  }
};

const handleDeleteChat = async (chatId) => {
  if (!confirm('确定要删除该会话及其所有聊天记录吗？')) return;
  try {
    await axios.delete(`/api/chat/delete/${chatId}`);
    // 删除本地chatList和messageList
    chatList.value = chatList.value.filter(chat => chat.id !== chatId);
    if (selectedChatId.value === chatId) {
      selectedChatId.value = chatList.value.length ? chatList.value[0].id : null;
      if (selectedChatId.value) {
        fetchMessageList(selectedChatId.value);
      } else {
        messageList.value = [];
      }
    }
  } catch (e) {
    ElMessage.error('删除失败');
  }
};

const logout = () => {
  localStorage.removeItem('userId');
  router.push('/login');
};

function extractImageIds(answer) {
  // 匹配所有 [ID:x]，x为数字
  const matches = answer.match(/\[ID:(\d+)\]/g);
  if (!matches) return [];
  // 提取数字部分
  return matches.map(m => m.match(/\[ID:(\d+)\]/)[1]);
}

function getImageUrl(imgId, item) {
  // 如果你有图片URL数组，可以用item.imageUrls[imgId]，否则拼接
  return `/api/chat/image/${imgId}`;
}

onMounted(() => {
  if (!userId) {
    router.push('/login');
    return;
  }
  fetchChatList();
  document.body.style.overflow = 'hidden';
});
onUnmounted(() => {
  document.body.style.overflow = '';
});
</script>

<style scoped>
html, body, #app {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden; /* 只在/chat页面生效，防止全局滚动 */
}

.el-aside > div[style*='overflow-y: auto'] {
  flex: 1 1 auto;
  min-height: 0;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  background: #eee;
}

.chat-bubble {
  max-width: 400px;
  padding: 12px 18px;
  border-radius: 20px;
  font-size: 15px;
  word-break: break-all;
  line-height: 1.6;
}

.user-bubble {
  background: #aee1f9;
  color: #333;
  border-bottom-right-radius: 4px;
}

.assistant-bubble {
  background: #fff;
  color: #333;
  border-bottom-left-radius: 4px;
  border: 1px solid #e0e0e0;
}

.chat-bg {
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
  z-index: 0;
  width: 100%;
  height: 100%;
  background: url('/bg-culture.png') center center/cover no-repeat;
  opacity: 0.12;
  pointer-events: none;
}

.chat-root {
  height: 100vh;
  overflow: hidden;
}
.chat-container {
  height: 100vh;
}
.chat-header {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fff;
  box-shadow: 0 2px 8px #f0f1f2;
  height: 64px;
  line-height: 64px;
  font-size: 20px;
  font-weight: bold;
}
.chat-main {
  position: relative;
  height: calc(100vh - 64px); /* header高度 */
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.chat-scroll-area {
  flex: 1 1 auto;
  overflow-y: auto;
  padding: 24px;
  /* 聊天内容区滚动 */
}
.chat-input-bar {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;

  z-index: 10;
  box-shadow: 0 -2px 8px #f0f1f2;
  
}
</style>